import myReq from '../../request'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsInfo: {},
    items: [
      // {value: 'friends', name: '朋友代付'},
      { value: 'self', name: '微信支付' }
    ],
    //选择地址
    tag: {
      addrTag: false,
      carTag: false,
      payTag: false,
      shadowTag: true,
    },
    animationData: {},
    shadowAnimation: {},
    //生成订单
    token: "",
    address_id: '',
    coupon_money: '',
    money: '',
    shopping_car_ids: [],
    //去支付
    delivery_time: '',
    timeStamp: 'asfoys',
    nonceStr: '',
    package: '',
    signType: '',
    paySign: '',
    // 确认支付
    payStatus: false,
  },

  // 处理地址数据
  delAddr(addrs) {
    let tmp = []
    // 循环地址列表数据
    addrs.forEach(item => {
      let {
        address_id,
        procince,
        city,
        area,
        detailed,
        default: tacitly,
        name,
        phone
      } = item;
      // console.log('——item————>',item);
      // 设置是否为默认样式
      let isDefault = tacitly === 1 ? true : false
      // 地址id
      let addr_id = address_id
      // 拼接地址
      let addr = procince + city + area + detailed
      //拿取姓名
      let chooseName = name
      //拿取电话
      let choosePhone = phone
      tmp.push({
        isDefault,
        addr_id,
        addr,
        chooseName,
        choosePhone
      })
    })
    // 循环处理过后的数据    
    tmp.forEach((item, index) => {
      // 如果是默认地址
      if (item.isDefault) {
        // 删除这条数据
        let firstAddr = tmp.splice(index, 1)[0]
        // 并将其推入数组第一个
        tmp.unshift(firstAddr)
        // 设置默认展示的地址
        this.setData({
          choosedAddress: item,
        })
        console.log("————当前地址：choosedAddress —————>", this.data.crrchoosedAddress);
      }
    })
    return tmp
  },

  // 去添加地址
  toAddAddr() {
    const that = this
    //跳转地址添加——>返回时跟新地址选择列表
    wx.navigateTo({
      url: '../../pages/addAddress/addAddress',
      events:{
        addrSuccess:function(data){
          const addrList = data.data.data
          const deledAddrs = that.delAddr(addrList)
          that.setData({
            addrList,
            deledAddrs
          })
        }
      }
    })

  },

  // 打开选择地址列表
  openAddr() {
    let tag = this.data.tag
    tag.addrTag = true
    this.setData({
      tag,
      nowPop: "addrTag"
    })
    this.openShadow()

    let animation = wx.createAnimation({
      duration: 300
    })
    animation.height(this.data.boxH).opacity(1).step()
    this.setData({
      animationData: animation.export()
    })
  },

  // 关闭地址选择列表
  closeAddr() {
    let animation = wx.createAnimation({
      duration: 300
    })
    animation.height(0).opacity(0).step()
    this.setData({
      animationData: animation.export()
    })
    setTimeout(() => {
      let tag = this.data.tag
      tag.addrTag = false
      this.setData({
        tag,
        nowPop: ""
      })
      this.closeShadow()
    }, 300)
  },

  // 选择地址
  chooseAddr(e) {
    const {
      addrIndex
    } = e.currentTarget.dataset;

    console.log('——地址索引————>', addrIndex);

    let data = this.data.deledAddrs
    console.log('——data————>', data);
    let firstAddr = data.splice(addrIndex, 1)[0]
    data.unshift(firstAddr)
    this.setData({
      deledAddrs: data,
      choosedAddress: firstAddr,
      addrTag: false
    })
    this.closeAddr()
  },

  // 打开遮罩层
  openShadow() {
    let tag = this.data.tag
    tag.shadowTag = false
    this.setData({
      tag
    })
  },


  // 关闭遮罩层
  closeShadow() {
    let tag = this.data.tag
    tag.shadowTag = true
    this.setData({
      tag
    })
  },

  // 关闭弹出层
  closePop() {
    if (this.data.nowPop === "addrTag") {
      let animation = wx.createAnimation({
        duration: 300
      })
      animation.height(0).opacity(0).step()
      this.setData({
        animationData: animation.export()
      })
    } else {
      this.selectComponent("#config").closePop()
    }

    this.closeShadow()
    setTimeout(() => {
      let nowPop = this.data.nowPop
      let tag = this.data.tag
      tag[nowPop] = false
      this.setData({
        tag,
        nowPop: ""
      })
    }, 300)
  },

  //变更支付方式
  // radioChange(e) {
  //   console.log('radio发生change事件，携带value值为：', e.detail.value)

  //   const items = this.data.items
  //   for (let i = 0, len = items.length; i < len; ++i) {
  //     items[i].checked = items[i].value === e.detail.value
  //   // console.log('radio发生change items值为：', items[i].value)
  //   }
  //   // console.log('radio发生change items值为：', items[i].value)
  //   this.setData({
  //     items
  //   })
  // },

  // 去支付
  goPay: function (obj) {
    wx.showLoading({
      title: '加载中',
    })
    let that = this;
    // console.log("—1—token————>", that.data.token);
    // console.log("—2—地址id————>", JSON.stringify(that.data.choosedAddress.addr_id));
    console.log("—2—地址id————>", that.data.choosedAddress);
    // console.log("—3—金额money————>", that.data.money);
    // console.log("—4—购物车id————>", JSON.parse(that.data.shopping_car_ids));
    // console.log("—5—递送时间————>", that.data.delivery_time);

    if(that.data.choosedAddress === undefined){
        wx.showToast({
            title: '请检查收货地址信息是否存在遗漏',
            icon: 'none',
            duration: 2000
        })
    }

    let getToken = new Promise((resolve, reject) => {
      wx.getStorage({
        key: 'token',
        success(res) {
          resolve(res.data)
        }
      })
    })

    //生成订单&支付
    getToken.then(
      res => {
        // 获取地址数据
        myReq({
          url: 'http://api_dev.wanxikeji.cn/api/generateOrder',
          method: "POST",
          data: {
            token: res,
            address_id: JSON.stringify(that.data.choosedAddress.addr_id),
            // coupon_money: "0",
            money: that.data.money,
            shopping_car_ids: JSON.parse(that.data.shopping_car_ids),
            // delivery_time: JSON.stringify(that.data.delivery_time)
          },
        }).then(
          res => {
            console.log("——签名数据源：————>", res);

            let packageinfo = 'prepay_id=' + res.data.data.prepay_id;
            console.log('———预支付id————>', packageinfo);
    
            that.setData({
              timeStamp: res.data.data.timeStamp,
              nonceStr: res.data.data.nonce_str,
              package: packageinfo,
              signType: 'MD5',
              paySign: res.data.data.paySign
            })
            // console.log("—— 时间戳 ————>",that.data.timeStamp);
            // console.log("—— 随机字符 ————>",that.data.nonceStr);
            // console.log("—— 预支付id ————>",that.data.package);
            // console.log("—— 签名 ————>",that.data.paySign);
            //请求支付
             
              wx.hideLoading()
            wx.requestPayment({
              timeStamp: that.data.timeStamp,
              nonceStr: that.data.nonceStr,
              package: that.data.package,
              signType: that.data.signType,
              paySign: that.data.paySign,
              success: function (res) {

                console.log("支付成功");
                wx.reLaunch({
                  url: '../order_Form/order_Form'
                })
              },
              fail: function (res) {
                console.log("支付失败！");
                // wx.showToast({
                //   title: '支付失败！',
                //   icon: 'none',
                //   duration: 2000
                // })
                wx.reLaunch({
                  url: '../wait_Pay/wait_Pay'
                })
              }
            })    
          },
          err => {
            console.log("请求失败")
          }
        )
      }
    )
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    //拿取token及地址列表
    let getToken = new Promise((resolve, reject) => {
      wx.getStorage({
        key: 'token',
        success(res) {
          resolve(res.data)
        }
      })
    })

    //获取token-1:引入了request.js拦截器
    getToken.then(
      res => {
        // 获取地址数据
        myReq({
          url: 'http://api_dev.wanxikeji.cn/api/userAddressList',
          method: "POST",
          data: {
            token: res
          },
        }).then(
          res => {
            console.log(res.data.data)
            for (let i = 0; i < res.data.data.length; i++) {
              let address=res.data.data[i].procince+res.data.data[i].city+res.data.data[i].area+res.data.data[i].detailed
           if (address==wx.getStorageSync('detaddress').addr) {
             let add={
              chooseName:res.data.data[i].name,
              addr:address,
              choosePhone:res.data.data[i].phone,
             }
           that.setData({
                choosedAddress:add
            })
            console.log(that.data.choosedAddress);
           }
            }
            const addrList = res.data.data
            const deledAddrs = that.delAddr(addrList)
            that.setData({
              addrList,
              deledAddrs
            })
          },
          err => {
            // console.log(err)
            const addrList = []
            const deledAddrs= []
            that.setData({
              addrList,
              deledAddrs
            })
          }
        )
      },
      err => {
        wx.redirectTo({
          url: '../myinfo/myinfo'
        })
      }
    )

    //获取token-2:未采用封装的request.js拦截器
    // wx.getStorage({
    //   key: 'token',
    //   success(res) {
    //     // console.log(res)
    //     that.setData({ token: res.data })
    //     wx.request({
    //       url: 'http://api_dev.wanxikeji.cn/api/userAddressList',
    //       method: "POST",
    //       data: {
    //         token: that.data.token
    //       },
    //       success(response) {
    //         console.log('———username——————————>', response.data.data[0].name);
    //         const addrList = response.data.data
    //         const deledAddrs = that.delAddr(addrList)
    //         that.setData({
    //           addrList,
    //           deledAddrs
    //         })
    //       },
    //     })
    //   }
    // })

    wx.getSystemInfo({
      success: res => {
        //导航高度
        console.log(res)
        let navH = res.statusBarHeight + 46
        let boxH = res.windowHeight - navH
        this.setData({
          navH,
          boxH
        });
      },
      fail(err) {
        console.log(err);
      }
    })

    //发货时间
    var currDate = (new Date()).valueOf();
    var deliveryData = Math.floor((currDate + 43200) / 1000);
    console.log("——发货时间————>", deliveryData);

    //接收购物车传参 ——> 生成订单
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('transfer', function (data) {
      // console.log("接收到购物车传来的参数->",data)
      // console.log("购物车id->",data.data.shoppingCarIds)
      that.setData({
        goodsInfo: data.data,
        money: data.data.allPrice,
        shopping_car_ids: JSON.stringify(data.data.shoppingCarIds),
        delivery_time: deliveryData
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})